from flask import Blueprint, jsonify, request
from flask_jwt_extended import (get_jwt_identity, jwt_required)
import json
import logging

logger = logging.getLogger(__name__)

from flaskapp.services.alarm import alarm_delete, alarm_get, alarm_insert

alarm_bp = Blueprint('alarm', __name__)

@alarm_bp.route('/api/alarm', methods=['GET'])
# @jwt_required()
def get_data():
    try:
        if request.is_json:
            json_data = request.get_json()
            pageIndex = json_data.get('pageIndex', 1)
            pageSize = json_data.get('pageSize', 10)
            classType = json_data.get('classType', None)
        else:
            pageIndex = request.args.get('pageIndex', default=1, type=int)
            pageSize = request.args.get('pageSize', default=10, type=int)
            classType = request.args.get('classType', default=None, type=str)
        
        logger.info(f"Request received for pageIndex: {pageIndex}, pageSize: {pageSize}, classType: {classType}")
        data = alarm_get(page=pageIndex, per_page=pageSize, classType=classType)
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})

@alarm_bp.route('/api/alarm', methods=['POST'])
def post_data():
    try:
        if request.is_json:
            data_list = request.get_json()
        else:
            return jsonify({"error": "Invalid input format, expected JSON array"}), 400

        success_count = 0

        for data in data_list:
            if isinstance(data.get('box'), str):
                data['box'] = json.loads(data['box'])

            result = alarm_insert(data['box'], data['classType'], data['confidence'], data['file_path'], data['target'], data['mediaID'])
            if result:
                success_count += 1

        if success_count == len(data_list):
            return jsonify({"code": 0, "success": True})
        else:
            return jsonify({"error": "Failed to insert some data", "success_count": success_count})
    except ValueError as ve:
        logger.error(f"Validation error: {ve}")
        return jsonify({"error": str(ve)})
    except Exception as e:
        logger.error(f"Error inserting data: {e}")
        return jsonify({"error": "Failed to insert data"})


@alarm_bp.route('/api/alarm/<string:alarm_id>', methods=['DELETE'])
@jwt_required()
def delete_data(alarm_id):
    try:
        result = alarm_delete(alarm_id)
        if result:
            return jsonify({"code": 0, "success": True})
        else:
            return jsonify({"error": "Alarm not found"})
    except Exception as e:
        logger.error(f"Error deleting data: {e}")
        return jsonify({"error": "Failed to delete data"})
    



